/*
 * Copyright (C) 2015 Evgeniy Egorov
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package ru.apertum.journal.forms;

import java.awt.Desktop;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ResourceBundle;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import ru.apertum.journal.IDocController;
import ru.apertum.journal.model.Attached;
import ru.apertum.journal.model.Document;
import ru.apertum.journal.model.Storage;
import ru.apertum.journal.model.Visit;
import ru.apertum.journal.model.patients.AttachedTableModel;
import ru.apertum.qsystem.client.Locales;
import ru.apertum.qsystem.common.QLog;
import ru.apertum.qsystem.common.Uses;
import ru.apertum.qsystem.common.exceptions.ClientException;

/**
 *
 * @author Evgeniy Egorov
 */
public class FDocMaster extends javax.swing.JDialog {

    final private Visit visit;
    final private Document doc;
    final private IDocController blanc;
    public static JLabel hackState;
    private static final ResourceBundle trn = ResourceBundle.getBundle("ru/apertum/journal/forms/resources/FJournal", Locales.getInstance().getLangCurrent());

    /**
     * Creates new form FDocMaster2
     *
     * @param parent
     * @param modal
     * @param visit
     * @param blanc
     * @param doc
     */
    public FDocMaster(java.awt.Frame parent, boolean modal, Visit visit, IDocController blanc, Document doc) {
        super(parent, modal);
        initComponents();

        setTitle(blanc.getName());
        this.visit = visit;
        this.doc = doc;
        this.blanc = blanc;
        this.tfNumber.setText(doc.getNumber());
        this.labelDate.setText(Uses.format_dd_MMMM_yyyy.format(doc.getDate()));
        try {
            setIconImage(ImageIO.read(FDocMaster.class.getResource("/ru/apertum/journal/forms/resources/favicon_blue.png")));
        } catch (IOException ex) {
            System.err.println(ex);
        }
        // свернем по esc
        getRootPane().registerKeyboardAction((ActionEvent e) -> {

            setVisible(false);
        },
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);

        panel.setLayout(new GridLayout(1, 1));
        panel.add(blanc.getGUI());

        attachedTable.getColumnModel().getColumn(0).setPreferredWidth(10);
        attachedTable.getColumnModel().getColumn(0).setWidth(10);
        attachedTable.getColumnModel().getColumn(0).setMaxWidth(50);
        attachedTable.getColumnModel().getColumn(0).setPreferredWidth(50);
        attachedTable.getColumnModel().getColumn(0).setMaxWidth(1000);

        //таблица приложений
        ((AttachedTableModel) (attachedTable.getModel())).update(doc.getAttached());
    }

    private boolean result = false;

    public String getNumber() {
        return tfNumber.getText();
    }

    public boolean getResult() {
        return result;
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel5 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        buttonOK = new javax.swing.JButton();
        buttonCancel = new javax.swing.JButton();
        buttonPrint = new javax.swing.JButton();
        buttonExport = new javax.swing.JButton();
        buttonApply = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel4 = new javax.swing.JPanel();
        panel = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jPanel7 = new javax.swing.JPanel();
        btnRemoveAttached = new javax.swing.JButton();
        btnAddAttached = new javax.swing.JButton();
        btnEditAttached = new javax.swing.JButton();
        btnDownloadAttached = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        attachedTable = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        tfNumber = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        labelDate = new javax.swing.JTextField();

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowDeactivated(java.awt.event.WindowEvent evt) {
                formWindowDeactivated(evt);
            }
        });

        jPanel1.setBorder(new javax.swing.border.MatteBorder(null));

        buttonOK.setBackground(new java.awt.Color(0, 255, 0));
        buttonOK.setText(trn.getString("ok")); // NOI18N
        buttonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonOKActionPerformed(evt);
            }
        });

        buttonCancel.setBackground(new java.awt.Color(255, 0, 0));
        buttonCancel.setText(trn.getString("cancel")); // NOI18N
        buttonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelActionPerformed(evt);
            }
        });

        buttonPrint.setText(trn.getString("print")); // NOI18N
        buttonPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonPrintActionPerformed(evt);
            }
        });

        buttonExport.setText(trn.getString("export")); // NOI18N
        buttonExport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonExportActionPerformed(evt);
            }
        });

        buttonApply.setBackground(new java.awt.Color(255, 255, 0));
        buttonApply.setText(trn.getString("apply")); // NOI18N
        buttonApply.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonApplyActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(buttonPrint)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonExport)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(buttonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(buttonApply, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(buttonOK, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonOK)
                    .addComponent(buttonCancel)
                    .addComponent(buttonPrint)
                    .addComponent(buttonExport)
                    .addComponent(buttonApply))
                .addContainerGap())
        );

        jPanel2.setBorder(new javax.swing.border.MatteBorder(null));

        javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
        panel.setLayout(panelLayout);
        panelLayout.setHorizontalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        panelLayout.setVerticalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab(trn.getString("params"), jPanel4); // NOI18N

        jPanel7.setBorder(new javax.swing.border.MatteBorder(null));

        btnRemoveAttached.setBackground(new java.awt.Color(255, 0, 0));
        btnRemoveAttached.setText(trn.getString("remove")); // NOI18N
        btnRemoveAttached.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveAttachedActionPerformed(evt);
            }
        });

        btnAddAttached.setBackground(new java.awt.Color(0, 255, 0));
        btnAddAttached.setText(trn.getString("add")); // NOI18N
        btnAddAttached.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddAttachedActionPerformed(evt);
            }
        });

        btnEditAttached.setBackground(new java.awt.Color(255, 255, 0));
        btnEditAttached.setText(trn.getString("edit")); // NOI18N
        btnEditAttached.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditAttachedActionPerformed(evt);
            }
        });

        btnDownloadAttached.setText(trn.getString("download")); // NOI18N
        btnDownloadAttached.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDownloadAttachedActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnDownloadAttached)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnRemoveAttached)
                .addGap(18, 18, 18)
                .addComponent(btnEditAttached)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAddAttached)
                .addContainerGap())
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnRemoveAttached)
                    .addComponent(btnAddAttached)
                    .addComponent(btnEditAttached)
                    .addComponent(btnDownloadAttached))
                .addContainerGap())
        );

        attachedTable.setModel(new AttachedTableModel());
        jScrollPane1.setViewportView(attachedTable);

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 698, Short.MAX_VALUE)
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jTabbedPane1.addTab(trn.getString("attachment"), jPanel6);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1)
        );

        jPanel3.setBorder(new javax.swing.border.MatteBorder(null));

        jLabel1.setText(trn.getString("doc_num")); // NOI18N

        jLabel3.setText(trn.getString("doc_date")); // NOI18N

        labelDate.setEditable(false);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tfNumber)
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelDate, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addComponent(labelDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOKActionPerformed
        if (apply()) {
            setVisible(false);
        }
    }//GEN-LAST:event_buttonOKActionPerformed

    private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
        setVisible(false);
    }//GEN-LAST:event_buttonCancelActionPerformed

    private void buttonExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExportActionPerformed
        blanc.export();
    }//GEN-LAST:event_buttonExportActionPerformed

    private void buttonPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPrintActionPerformed
        blanc.print();
    }//GEN-LAST:event_buttonPrintActionPerformed

    private void btnRemoveAttachedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveAttachedActionPerformed
        removeAttached();
    }//GEN-LAST:event_btnRemoveAttachedActionPerformed

    private void btnAddAttachedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddAttachedActionPerformed
        if (doc == null || doc.getId() == null) {
            JOptionPane.showMessageDialog(this,
                    trn.getString("doc_changet_need_save"),
                    trn.getString("new_att"),
                    JOptionPane.OK_OPTION);
        } else {
            addNewAttahed();
        }
    }//GEN-LAST:event_btnAddAttachedActionPerformed

    private void btnEditAttachedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditAttachedActionPerformed
        editAttached();
    }//GEN-LAST:event_btnEditAttachedActionPerformed

    private void btnDownloadAttachedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDownloadAttachedActionPerformed
        try {
            downloadAttached();
        } catch (IOException ex) {
            throw new RuntimeException("No blob. ", ex);
        }
    }//GEN-LAST:event_btnDownloadAttachedActionPerformed

    private void formWindowDeactivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowDeactivated
        result = false;
    }//GEN-LAST:event_formWindowDeactivated

    private void buttonApplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonApplyActionPerformed
        if (apply()) {
            JOptionPane.showMessageDialog(this,
                    trn.getString("doc_was_saved"),
                    trn.getString("saving"),
                    JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_buttonApplyActionPerformed

    private boolean apply() {
        // Обязательные поля
        if (tfNumber.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null,
                    trn.getString("need_doc_num"),
                    trn.getString("not_enauht_data"),
                    JOptionPane.NO_OPTION);
            tfNumber.requestFocusInWindow();
            return false;
        }

        if (doc == null) {
            throw new RuntimeException("No document!");
        }
        final Document doc2 = blanc.saveDocData();
        doc.setNumber(getNumber());
        doc.setDocData(doc2.getDocData());
        //Document.saveDoc(doc);
        if (!visit.getDocs().contains(doc)) {
            visit.getDocs().add(doc);
        }

        try {
            Document.saveDoc(doc);
        } catch (ClientException ex) {
            System.err.println(ex);
            JOptionPane.showMessageDialog(this,
                    trn.getString("err_save_doc"),
                    trn.getString("saving"),
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }

        result = true;
        return true;
    }

    public void addNewAttahed() {

        QLog.l().logger().trace("Добавим новое вложение пациенту.");
        // если сегодня уже создали визит то его не нужно еще раз создавать, просто покажем его

        if (JOptionPane.showConfirmDialog(this,
                trn.getString("will_new_att_for_doc"),
                trn.getString("new_att"),
                JOptionPane.YES_NO_OPTION) == 1) {
            return;
        }
        final FAttachedDlg aa = new FAttachedDlg(null, true);
        Uses.setLocation(aa);
        aa.setVisible(true);
        if (aa.isOK()) {
            final Attached att;
            doc.getAttached().add(att = new Attached(doc));
            att.setFileName(aa.getFile().getName());
            att.setTitle(aa.getTitleDoc());
            att.setComments(aa.getComment());
            try {
                Attached.saveAttached(att);
                Storage.saveStorage(aa.getFile(), att.getId(), null, null, doc.getId(), att.getTitle());
            } catch (ClientException ex) {
                JOptionPane.showMessageDialog(this,
                        trn.getString("err_create_att"),
                        trn.getString("saving_att"),
                        JOptionPane.ERROR_MESSAGE);
                return;
            }

            ((AttachedTableModel) attachedTable.getModel()).update(doc.getAttached());
            ((AttachedTableModel) attachedTable.getModel()).fireTableDataChanged();
        } else {
            if (aa.isOKpress()) {
                JOptionPane.showMessageDialog(this,
                        trn.getString("discorrec_data_for_att"),
                        trn.getString("new_att"),
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    public void removeAttached() {
        if (!attachedTable.getSelectionModel().isSelectionEmpty()) {
            QLog.l().logger().trace("Удалим вложение клиента.");
            int row = attachedTable.convertRowIndexToModel(attachedTable.getSelectedRow());
            AttachedTableModel model = (AttachedTableModel) attachedTable.getModel();

            final Attached attached = model.getRowAt(row);
            if (attached == null || JOptionPane.showConfirmDialog(this,
                    java.text.MessageFormat.format(java.util.ResourceBundle.getBundle("ru/apertum/journal/forms/resources/FJournal").getString("will_add_remove"), new Object[]{attached.getTitle()}),
                    trn.getString("remove_att"),
                    JOptionPane.YES_NO_OPTION) == 1) {
                return;
            }
            QLog.l().logger().debug(java.text.MessageFormat.format(java.util.ResourceBundle.getBundle("ru/apertum/journal/forms/resources/FJournal").getString("removing_the_att"), new Object[]{attached.getTitle()}));
            // удалим навсегда

            doc.getAttached().remove(attached);
            model.removeAttached(attached);
            Attached.removeAttached(attached);
        }
    }

    public void editAttached() {
        if (!attachedTable.getSelectionModel().isSelectionEmpty()) {
            QLog.l().logger().trace("с вложение.");
            int row = attachedTable.convertRowIndexToModel(attachedTable.getSelectedRow());
            AttachedTableModel model = (AttachedTableModel) attachedTable.getModel();

            final Attached attached = model.getRowAt(row);

            QLog.l().logger().debug("Редактируем приложение \"" + attached.getTitle() + "\"");
            // удалим навсегда
            final FAttachedDlg aa = new FAttachedDlg(null, true);
            Uses.setLocation(aa);
            aa.setComment(attached.getComments());
            aa.setTitleDoc(attached.getTitle());
            aa.setNoFile();

            aa.setVisible(true);
            if (aa.isOKnoFile()) {
                attached.setTitle(aa.getTitleDoc());
                attached.setComments(aa.getComment());
                try {
                    Attached.saveAttached(attached);
                } catch (ClientException ex) {
                    JOptionPane.showMessageDialog(this,
                            trn.getString("error_create_att"),
                            trn.getString("saving_att"),
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }

                ((AttachedTableModel) attachedTable.getModel()).update(doc.getAttached());
                ((AttachedTableModel) attachedTable.getModel()).fireTableDataChanged();
            }
        }
    }

    public void downloadAttached() throws FileNotFoundException, IOException {

        if (!attachedTable.getSelectionModel().isSelectionEmpty()) {
            QLog.l().logger().trace("Загрузим вложение.");
            int row = attachedTable.convertRowIndexToModel(attachedTable.getSelectedRow());
            AttachedTableModel model = (AttachedTableModel) attachedTable.getModel();

            final Attached attached = model.getRowAt(row);
            if (attached == null) {
                return;
            }
            QLog.l().logger().debug("Загрузим приложение \"" + attached.getTitle() + "\"");

            final byte[] bb = Storage.loadStorage(attached.getId());

            final JFileChooser fc = new JFileChooser();
            fc.setDialogTitle(trn.getString("saving_att"));
            fc.setCurrentDirectory(new File("."));
            fc.setSelectedFile(new File(attached.getFileName()));
            if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                if (fc.getSelectedFile().exists() && JOptionPane.showConfirmDialog(this,
                        java.text.MessageFormat.format(java.util.ResourceBundle.getBundle("ru/apertum/journal/forms/resources/FJournal").getString("replace_file"), new Object[]{fc.getSelectedFile().getName()}),
                        trn.getString("saving_att"),
                        JOptionPane.YES_NO_OPTION) == 1) {
                    return;
                }

                try (FileOutputStream outputStream = new FileOutputStream(fc.getSelectedFile())) {
                    outputStream.write(bb);
                    outputStream.flush();
                }

                final Desktop desktop = Desktop.getDesktop();
                desktop.open(fc.getSelectedFile().getParentFile());
            }
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable attachedTable;
    private javax.swing.JButton btnAddAttached;
    private javax.swing.JButton btnDownloadAttached;
    private javax.swing.JButton btnEditAttached;
    private javax.swing.JButton btnRemoveAttached;
    private javax.swing.JButton buttonApply;
    private javax.swing.JButton buttonCancel;
    private javax.swing.JButton buttonExport;
    private javax.swing.JButton buttonOK;
    private javax.swing.JButton buttonPrint;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTextField labelDate;
    private javax.swing.JPanel panel;
    private javax.swing.JTextField tfNumber;
    // End of variables declaration//GEN-END:variables
}
